var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var CommentSchame = new Schema({
    blog: {
        type: Schema.Types.ObjectId,
        ref: 'Blog'
    },
    from: {
        type: Schema.Types.ObjectId,
        ref: 'User'
    },
    reply: [{
        from: {
            type: Schema.Types.ObjectId,
            ref: 'User'
        },
        to: {
            type: Schema.Types.ObjectId,
            ref: 'User'
        },
        content: String,
        meta:{
            createAt:{
                type:Date,
                default:Date.now()
            }
        }
    }],
    content: String,
    meta: {
        createAt: { //创建时间
            type: Date,
            default: Date.now()
        },
        updataAt: { //更新时间
            type: Date,
            default: Date.now()
        }
    }
});

CommentSchame.pre('save', function(next) {
    var comment = this;
    if (comment.isNew) {
        comment.meta.createAt = comment.meta.updataAt = Date.now();
    } else {
        comment.meta.updataAt = Date.now();
    }
    next();
});


CommentSchame.statics = {
    fetch: function(cb) {
        return this
            .find({})
            .sort({
                'meta.createAt': -1
            })
            .exec(cb)
    },
    fetchByAttr: function(value, cb) {
        return this
            .find(value)
            .sort('meta.createAt')
            .exec(cb)
    },
    findOneByAttr: function(value, cb) {
        return this
            .findOne(value)
            .exec(cb)
    },
    top: function(cb) {
        return this
            .find({})
            .skip(1 * (10 - 1), cb)
            .limit(100)
            .sort('meta.createAt')
            .exec(cb)
    }
}

module.exports = CommentSchame;
